<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <el-input v-model="listQuery.searchMsg" placeholder="搜索名称" style="width: 200px;" class="filter-item filter-input"
                @keyup.enter.native="handleFilter"/>
      <el-button style="margin-left: 10px;" class="filter-item" type="primary" icon="el-icon-search"
                 @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add" style="margin-left: 10px;margin-right: 10px" type="primary"
                 icon="el-icon-circle-plus-outline"
                 @click="toSelect">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50">
      </el-table-column>
      <!-- <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.Index }}
        </template>
      </el-table-column> -->

      <el-table-column label="名称" width="230" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="病人信息" align="center">
        <template slot-scope="scope">
          <span>{{ truncatedText(scope.row.caseJson) }}</span>

        </template>
      </el-table-column>

      <el-table-column label="详细信息" align="center">
        <template slot-scope="scope">
          <span>{{ truncatedText(scope.row.itemJson) }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="success" size="mini" @click="download(row)">
            下载
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="Form" label-position="left" label-width="90px"
      >

        <el-form-item label="名称" prop="username">
          <el-input v-model="Form.name"/>
        </el-form-item>

        <el-row>
          <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
            <div class="sub-title">术式</div>
            <el-select v-model="Form.operationName" clearable placeholder="请选择" @change="handleChangeOP">
              <el-option
                v-for="item in listOptions(operationMsg)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click.native.stop="selectOP( item.value,item.label)"
              >
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
            <div class="sub-title">设备</div>
            <el-select v-model="Form.deviceName" clearable placeholder="请选择" @change="handleChangeDI">
              <el-option
                v-for="item in listOptions(deviceMsg)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click.native.stop="selectDi( item.value,item.label)">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6" style="padding-right: 10px;padding-left: 10px">
            <div class="sub-title">器官部位</div>
            <el-select v-model="Form.organsName" clearable placeholder="请选择" @change="handleChangeOR">
              <el-option
                v-for="item in listOptions(organsMsg)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click.native.stop="selectOR( item.value,item.label)">
              </el-option>
            </el-select>
          </el-col>
        </el-row>


        <!--<el-form-item label="描述" prop="name">-->
        <!--<el-input v-model="Form.note"/>-->
        <!--</el-form-item>-->
        <div class="jsonBox">
          <div>
            <span>病人信息</span>
          </div>
          <el-row>
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px"
                    v-for="(item, index) in caseJson.caseValue" :key="index"
            >
              <div class="sub-title">{{item.name}}</div>
              <el-input v-if="item.valueType=='文本' || item.valueType=='数字'" v-model="item.value"
                        placeholder="请输入内容"></el-input>
              <el-select v-if="item.valueType=='单选'" v-model="item.value" placeholder="请选择">
                <el-option
                  v-for="item in parsedOptions(item.valueType,item.name,caseList)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-select v-if="item.valueType=='多选'" v-model="item.value" multiple placeholder="请选择">
                <el-option
                  v-for="item in parsedOptions(item.valueType,item.name,caseList)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>

              <el-time-picker v-if="item.valueType=='时间'"
                              v-model="item.value"
                              format="HH:mm:ss"
                              value-format="HH:mm:ss"
                              placeholder="任意时间点">
              </el-time-picker>

              <el-date-picker v-if="item.valueType=='日期'"
                              v-model="item.value"
                              type="date"
                              placeholder="选择日期"
                              format="yyyy-MM-dd"
                              value-format="yyyy-MM-dd"
              >
              </el-date-picker>

            </el-col>

          </el-row>

        </div>
        <div class="jsonBox">
          <div>
            <span>详细信息</span>
          </div>
          <el-row>
            <el-col :span="6" style="padding-right: 10px;padding-left: 10px"
                    v-for="(item, index) in itemJson.itemValue" :key="index">
              <div class="sub-title">{{item.name}}</div>
              <el-input v-if="item.valueType=='文本' || item.valueType=='数字'" v-model="item.value"
                        placeholder="请输入内容"></el-input>
              <el-select v-if="item.valueType=='单选'" v-model="item.value" placeholder="请选择">
                <el-option
                  v-for="item in parsedOptions(item.valueType,item.name,itemList)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-select v-if="item.valueType=='多选'" v-model="item.value" multiple placeholder="请选择">
                <el-option
                  v-for="item in parsedOptions(item.valueType,item.name,itemList)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>


              <el-time-picker v-if="item.valueType=='时间'"
                              v-model="item.value"
                              format="HH:mm:ss"
                              value-format="HH:mm:ss"
                              placeholder="任意时间点">
              </el-time-picker>

              <el-date-picker v-if="item.valueType=='日期'"
                              v-model="item.value"
                              type="date"
                              placeholder="选择日期">
              </el-date-picker>

            </el-col>

          </el-row>

        </div>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {IgsReportAPI} from '../../../api/igs/report'
  import {IgsConfigAPI} from '../../../api/igs/igsConfig'
  import {OperationAPI} from '../../../api/igs/operation'
  import {IgsDeviceAPI} from '../../../api/igs/device'
  import {IgsOrgansAPI} from '../../../api/igs/organs'
  import {merge} from '../../../api/igs/merge'

  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    components: {Pagination},
    name: 'user',
    data() {

      return {
        // caseMsg:{},
        list: null,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          searchMsg: '',
          orderby: 'ORDER BY `id` DESC'
        },
        dialogFormVisible: false,
        dialogStatus: "create",
        title: "",

        Form: {
          id: null,
          name: '',
          node: '',
          operationName: '',
          operationId: 0,
          deviceName: '',
          deviceId: 0,
          organsName: '',
          organesId: 0,
          caseId: 0,
          igsCase:{},
          caseJson: {
            caseValue: [{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          },
          itemJson: {
            itemValue: [{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          }

        },
        roles: null,
        caseJson: {
          caseValue: []
        },
        itemJson: {
          itemValue: []
        },
        caseList: null,
        itemList: null,
        typeValues: [
          {value: '文本'},
          {value: '数字'},
          {value: '时间'},
          {value: '日期'},
          {value: '单选'},
          {value: '多选'}
        ],
        addJson: {
          id: '',
          name: '',
          value: '',
          valueType: ''
        },
        operationMsg: [],
        deviceMsg: [],
        organsMsg: [],
        selectoperationMsg: null,
        selectdeviceMsg: null,
        selectorgansMsg: null,

      }
    },
    computed: {
      caseMsg() {
        console.log('in to caseMsg');

        return this.$store.getters['casep/getCaseMsg']; // B 直接等于 caseMsg
      }
    },
    mounted() {
      console.log('in to mounted', this.caseMsg);

      if (this.caseMsg.id > 0) {
        this.handleCreate();
      }
    },

    created() {
      this.fetchData()

    },

    methods: {
      download(item){
        // IgsReportAPI.downloadFile(item)

          // const url = 'http://192.168.10.80:870/datas/D/GK308/pdf/王芳考核评分表__2024112815583045.pdf';
        // let url = '/datas/D/GK308/pdf/王芳考核评分表__2024112815583045.pdf';
        let url = item.path;
          fetch(url, {
            method: 'GET',
            headers: new Headers({
              // 如果需要认证或其他头信息，可以在这里添加
            })
          })
            .then(response => {
              console.log('url:'+url);
              if (!response.ok) {
                throw new Error('Network response was not ok');
              }
              return response.blob(); // 将响应体转换为 Blob
            })
            .then(blob => {
              const link = document.createElement('a');
              link.href = URL.createObjectURL(blob);
              link.download = item.filename; // 设置下载的文件名
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link); // 下载完成后移除元素
            })
            .catch(error => console.error('There was a problem with the fetch operation:', error));

      },

      initList() {
        console.log('in to initList');
        this.caseJson.caseValue = [];
        this.itemJson.itemValue=[];



        this.setList(this.selectoperationMsg)
        this.setList(this.selectdeviceMsg)
        this.setList(this.selectorgansMsg)
        // 使用 forEach 遍历并更新符合条件的对象
        if(this.dialogStatus != 'update'){
          this.caseJson.caseValue.forEach(item => {
            // 手术日期
            // 住院号
            // 姓名
            // 年龄(岁)
            // 体重(KG)
            // 身高(CM)
            // 性别
            if (item.name === '手术日期') {
              item.value = this.caseMsg.surgeryDate;
            }
            if (item.name === '住院号') {
              item.value = this.caseMsg.hospitalNumber;
            }
            if (item.name === '姓名') {
              item.value = this.caseMsg.name;
            }
            if (item.name === '年龄(岁)') {
              item.value = this.caseMsg.age;
            }
            if (item.name === '体重(KG)') {
              item.value = this.caseMsg.weight;
            }
            if (item.name === '身高(CM)') {
              item.value = this.caseMsg.stature;
            }
            if (item.name === '性别') {
              item.value = this.caseMsg.sex;
            }
          })
        }
        else {

          this.caseJson.caseValue.forEach(item => {
            // 手术日期
            // 住院号
            // 姓名
            // 年龄(岁)
            // 体重(KG)
            // 身高(CM)
            // 性别
            if (item.name === '手术日期') {
              item.value = this.Form.igsCase.surgeryDate;
            }
            if (item.name === '住院号') {
              item.value = this.Form.igsCase.hospitalNumber;
            }
            if (item.name === '姓名') {
              item.value = this.Form.igsCase.name;
            }
            if (item.name === '年龄(岁)') {
              item.value = this.Form.igsCase.age;
            }
            if (item.name === '体重(KG)') {
              item.value = this.Form.igsCase.weight;
            }
            if (item.name === '身高(CM)') {
              item.value = this.Form.igsCase.stature;
            }
            if (item.name === '性别') {
              item.value = this.Form.igsCase.sex;
            }
          })
        }

      },

      setList(foundItem) {
        console.log('in to setList');
        if (foundItem == null) {
          console.log('in to return');
          return
        }

        console.log('foundItem:', foundItem);
// 然后解析内层的caseJson字符串为JSON对象
        let caseJson = JSON.parse(foundItem.caseJson);
// 提取caseValue数组
        let caseValueArray = caseJson.caseValue;
        console.log(caseValueArray); // 输出caseValue数组
        this.caseJson.caseValue = merge.mergeValues(this.caseJson.caseValue, JSON.parse(JSON.stringify(caseValueArray)))
        // this.caseJson.caseValue = JSON.parse(JSON.stringify(caseValueArray));
        console.log('this.caseJson.caseValue:', this.caseJson.caseValue);
        //  caseValue 数组中的每个对象值的value设置为''
        if (this.caseJson.caseValue != null && this.dialogStatus != 'update') {
          this.caseJson.caseValue = this.caseJson.caseValue.map(item => ({
            ...item, // 复制对象的所有属性
            value: '' // 设置 'value' 属性为 ''
          }));
        }
        console.log('in to itemJson', foundItem);

        let itemJson = JSON.parse(foundItem.itemJson);
        console.log(itemJson); //
// 提取itemValue数组
        let itemValueArray = itemJson.itemValue;
        console.log(itemValueArray); // 输出caseValue数组
        // this.itemJson.itemValue = JSON.parse(JSON.stringify(itemValueArray));
        this.itemJson.itemValue = merge.mergeValues(this.itemJson.itemValue, JSON.parse(JSON.stringify(itemValueArray)))
        console.log('this.itemJson.itemValue:', this.itemJson.itemValue);
        //  caseValue 数组中的每个对象值的value设置为''
        if (this.itemJson.itemValue != null  ) {
          this.itemJson.itemValue = this.itemJson.itemValue.map(item => ({
            ...item, // 复制对象的所有属性
            value: '' // 设置 'value' 属性为 ''
          }));
        }

      },

      handleChangeOP(value) {
        if (!value) {
          this.selectoperationMsg = null
        }
      },
      handleChangeDI(value) {
        if (!value) {
          this.selectdeviceMsg = null
        }
      },
      handleChangeOR(value) {
        if (!value) {
          this.selectorgansMsg = null
        }
      },

      selectOP(id, name) {
        // console.log('Selected id:', id);
        // console.log('Selected name:', name);
        this.Form.operationName = name;
        this.Form.operationId = id;
        console.log('operationMsg:', this.operationMsg);


        // 使用find方法找到name等于targetName的对象
        let foundItem = this.operationMsg.find(item => item.name === name);
        this.selectoperationMsg = JSON.parse(JSON.stringify(foundItem))

        // selectdeviceMsg: null,
        // selectorgansMsg: null,
        this.initList();

      },
      selectDi(id, name) {
        // console.log('Selected id:', id);
        // console.log('Selected name:', name);
        this.Form.deviceName = name;
        this.Form.deviceId = id;
        console.log('deviceMsg:', this.deviceMsg);


        // 使用find方法找到name等于targetName的对象
        let foundItem = this.deviceMsg.find(item => item.name === name);
        this.selectdeviceMsg = JSON.parse(JSON.stringify(foundItem))
        // selectdeviceMsg: null,
        // selectorgansMsg: null,
        this.initList();
        let da = {
          pid: id
        }
        IgsOrgansAPI.hasAllByPid(da).then(res => {
          this.organsMsg = res.data;
        })

      },
      selectOR(id, name) {
        // console.log('Selected id:', id);
        // console.log('Selected name:', name);
        this.Form.organsName = name;
        this.Form.organesId = id;
        console.log('organsMsg:', this.organsMsg);


        // 使用find方法找到name等于targetName的对象
        let foundItem = this.organsMsg.find(item => item.name === name);
        this.selectorgansMsg = JSON.parse(JSON.stringify(foundItem))
        // selectdeviceMsg: null,
        // selectorgansMsg: null,
        this.initList();
      },

      listOptions(list) {

        return list.map(item => ({
          value: item.id,
          label: item.name
        }));

      },

      //单选框，多选
      parsedOptions(type, name, list) {
         // console.log('in to parsedOptions', type, name);
        // console.log('in to parsedOptions', list);
        for (let i = 0; i < list.length; i++) {
          if (list[i].valueType == type && list[i].name == name) {
            return list[i].value.split(',').map(value => ({
              value: value,
              label: value
            }));
          }
        }

      },

      truncatedText(longText) {
        return longText.length > 30 ? longText.slice(0, 30) + '...' : longText;
      },

      fetchData() {
        this.listLoading = true
        IgsReportAPI.hasAllToPage(this.listQuery).then(response => {
          let list = response.data.list
          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })
        let da = {
          type: 1
        }
        IgsConfigAPI.hasAllByType(da).then(res => {
          this.caseList = res.data;

          // //复制
          // this.caseJson.caseValue = JSON.parse(JSON.stringify(this.caseList));
          // console.log('this.caseJson.caseValue:',this.caseJson.caseValue);
          // //  caseValue 数组中的每个对象值的value设置为''
          // this.caseJson.caseValue = this.caseJson.caseValue.map(item => ({
          //   ...item, // 复制对象的所有属性
          //   value: '' // 设置 'value' 属性为 ''
          // }));
        })
        da = {
          type: 0
        }
        IgsConfigAPI.hasAllByType(da).then(res => {
          this.itemList = res.data;
        })


        // operationMsg:[],
        //   deviceMsg:[],
        //   organsMsg:[],

        //  OperationAPI
        //   IgsDeviceAPI
        //   IgsOrgansAPI
        OperationAPI.hasAll(da).then(res => {
          this.operationMsg = res.data;
        })
        IgsDeviceAPI.hasAll(da).then(res => {
          this.deviceMsg = res.data;
        })


      },

      handleFilter() {
        //搜索
        this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
        this.fetchData()
      },
      toSelect(){
        this.$router.push({ path: '/case/igs/case' })
      },
      handleCreate() {
        //新增
        console.log('in to handleCreate');
        this.title = "新建信息表"
        this.dialogStatus = 'create'
        this.Form = {
          id: null,
          name: '',
          node: '',
          operationName: '',
          operationId: 0,
          deviceName: '',
          deviceId: 0,
          organsName: '',
          organesId: 0,
          caseId: this.caseMsg.id,
          igsCase:{},
          caseJson: {
            caseValue: []
          },
          itemJson: {
            itemValue: [{
              id: '',
              name: '',
              value: '',
              valueType: ''
            }]
          }
        }

        console.log('in to this.caseMsg', this.caseMsg);
        console.log('in to this.caseList', this.caseList);

        // this.caseJson.caseValue = this.caseList.slice();


        this.itemJson.itemValue = [{
          id: '',
          name: '',
          value: '',
          valueType: ''
        }]
        console.log('this.Form', this.Form);
        this.dialogFormVisible = true
        // setTimeout(() => {
        //   this.$refs['dataForm'].clearValidate();
        // }, 300)
      },
      handleUpdate(row) {
        console.log('in to handleUpdate',row);
        //编辑
        let da = {
          pid: row.deviceId
        }
        IgsOrgansAPI.hasAllByPid(da).then(res => {
          this.organsMsg = res.data;

          // // 使用find方法找到name等于targetName的对象
          let foundItem = this.operationMsg.find(item => item.name === row.operationName);
          this.selectoperationMsg = JSON.parse(JSON.stringify(foundItem))
          // // // 使用find方法找到name等于targetName的对象
          let foundItem2 = this.deviceMsg.find(item => item.name === row.deviceName);
          this.selectdeviceMsg = JSON.parse(JSON.stringify(foundItem2))
          // 使用find方法找到name等于targetName的对象
          // let foundItem3 = this.organsMsg.find(item => item.name === row.organsName);
          // this.selectorgansMsg = JSON.parse(JSON.stringify(foundItem3))
        })



        this.dialogFormVisible = true
        this.title = "修改"
        this.dialogStatus = 'update'
        this.Form = {
          id: row.id,
          name: row.name,
          node: row.node,
          igsCase:row.igsCase,
          caseId:row.caseId,
          operationName: row.operationName,
          operationId: row.operationId,
          deviceName: row.deviceName,
          deviceId: row.deviceId,
          organsName: row.organsName,
          organesId: row.organesId,
          caseJson: row.caseJson,
          itemJson: row.itemJson

        }

        // 使用JSON.parse()来解析字符串为JSON对象
        this.caseJson = JSON.parse(row.caseJson);
        this.itemJson = JSON.parse(row.itemJson);

        console.log(this.caseJson)
        console.log(this.itemJson)
        console.log(this.Form)
      },
      handleDelete(row, index) {
        //删除
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          IgsReportAPI.delete({id: row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
      },
      handleRefresh() {
        //列表刷新
        this.fetchData()
      },
      handleStatus(row) {
        //更改状态
        console.log(row)
      },
      createData() {
        console.log('in to updateData');
        console.log('this.Form', this.Form);
        console.log('this.caseJson', this.caseJson);
        console.log('this.itemJson', this.itemJson);
        // 将对象转换为JSON字符串
        let str = JSON.stringify(this.caseJson);
        this.Form.caseJson = str;
        str = JSON.stringify(this.itemJson);
        this.Form.itemJson = str;
        console.log('this.Form', this.Form);
        IgsReportAPI.add(this.Form).then(() => {
          this.fetchData()
          this.$store.dispatch('casep/updateCaseMsg', null)
          this.dialogFormVisible = false
        })
      },
      updateData() {
        console.log('in to updateData');
        console.log('this.Form', this.Form);
        console.log('this.caseJson', this.caseJson);
        console.log('this.itemJson', this.itemJson);
        // 将对象转换为JSON字符串
        let str = JSON.stringify(this.caseJson);
        this.Form.caseJson = str;
        str = JSON.stringify(this.itemJson);
        this.Form.itemJson = str;
        console.log('this.Form', this.Form);
        IgsReportAPI.update(this.Form).then(() => {
          this.fetchData()
          this.$store.dispatch('casep/updateCaseMsg', null)
          this.dialogFormVisible = false
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .filter-container {
    .filter-item {
      margin-bottom: 10px;
    }
    .filter-input {
      margin-left: 20px;
    }
    .add {
      float: right;
    }
  }

  .addBox {
    width: 100%;
    button {
      width: 300px;
      margin: 10px auto;
      position: relative;
      display: block;
    }
  }

  .el-date-editor {
    width: 100% !important;
  }
</style>
